//bange_body.cpp
//Copyright (C) 2010-2011 Oscar (.teri) Triano

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <bange_body.hpp>

bange::body::body(cpSpace *space){
	this->isstatic = false;
	this->hasgravity = true;
	this->thebody = cpBodyNew(INFINITY, INFINITY);
	this->space = space;
	cpSpaceAddBody(this->space, this->thebody);
}

bool bange::body::NewIndex(lua_State *vm){
	//body, key, data
	char key[64] = {0};
	strncpy(key, lua_tostring(vm, 2), 64);
	if (strcmp(key, "velx") == 0 && lua_isnumber(vm, 3)){
		cpVect vel = cpBodyGetVel(this->thebody);
		vel.x = lua_tonumber(vm, 3);
		cpBodySetVel(this->thebody, vel);
		return true;
	}
	else if (strcmp(key, "vely") == 0 && lua_isnumber(vm, 3)){
		cpVect vel = cpBodyGetVel(this->thebody);
		vel.y = lua_tonumber(vm, 3);
		cpBodySetVel(this->thebody, vel);
		return true;
	}
	return false;
}

bool bange::body::Index(lua_State *vm){
	//body, key
	char key[64] = {0};
	strncpy(key, lua_tostring(vm, 2), 64);
	if (strcmp(key, "velx") == 0){
		cpVect vel = cpBodyGetVel(this->thebody);
		lua_pushnumber(vm, vel.x);
		return true;
	}
	else if (strcmp(key, "vely") == 0){
		cpVect vel = cpBodyGetVel(this->thebody);
		lua_pushnumber(vm, vel.y);
		return true;
	}
	return false;
}

void bange::body::SetBodyX(cpFloat x){
	cpVect pos = cpBodyGetPos(this->thebody);
	pos.x = x;
	cpBodySetPos(this->thebody, pos);
}

void bange::body::SetBodyY(cpFloat y){
	cpVect pos = cpBodyGetPos(this->thebody);
	pos.y = y;
	cpBodySetPos(this->thebody, pos);
}

cpFloat bange::body::GetBodyX(){
	cpVect pos = cpBodyGetPos(this->thebody);
	return pos.x;
}

cpFloat bange::body::GetBodyY(){
	cpVect pos = cpBodyGetPos(this->thebody);
	return pos.y;
}

bange::body::~body(){
	cpSpaceRemoveBody(this->space, this->thebody);
	cpBodyDestroy(this->thebody);
}
